import {Plugin, TransformResult} from "vite"
import {TransformOptions} from "@babel/core";
const babel = require("@babel/core");

export interface VitePluginBabelConfig {
  babelConfig?: TransformOptions;
  filterFile?: RegExp
}

export default function vitePluginBabel(config?: VitePluginBabelConfig): Plugin {
  if(!config) {
    config = {}
  }
  return {
    name: 'vite:vite-plugin-babel',
    transform(code: string, id: string): Promise<TransformResult> | TransformResult {
      let map = null
      if (id.includes('node_modules')) {
        return {code, map}
      }
      if (!config.filterFile) {
        config.filterFile = /\.(vue|js|jsx|ts|tsx)$/
      }
      if (config.filterFile.test(id)) {
        const babelFileResult = babel.transformSync(code, {
          filename: id,
          ...config.babelConfig
        });
        code = babelFileResult.code
        map = babelFileResult.map
      }
      return {
        code,
        map
      }
    }
  }
}
